const db = require('../config/db');

const Table = {
  // 根据店铺ID获取所有桌位
  getTablesByShopId: (shopId) => {
    return new Promise((resolve, reject) => {
      const query = `
        SELECT * FROM table_info 
        WHERE shop_id = ? AND status != '停用'
        ORDER BY table_type, table_number
      `;
      db.query(query, [shopId], (error, results) => {
        if (error) {
          console.error('获取桌位列表失败:', error);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },

  // 获取店铺桌位状态统计
  getShopTableStatus: (shopId) => {
    return new Promise((resolve, reject) => {
      const query = `
        SELECT 
          COUNT(*) as total_tables,
          SUM(CASE WHEN status = '空闲' THEN 1 ELSE 0 END) as available_tables,
          SUM(CASE WHEN status = '占用' THEN 1 ELSE 0 END) as occupied_tables,
          SUM(CASE WHEN status = '预留' THEN 1 ELSE 0 END) as reserved_tables
        FROM table_info 
        WHERE shop_id = ? AND status != '停用'
      `;
      db.query(query, [shopId], (error, results) => {
        if (error) {
          console.error('获取桌位状态失败:', error);
          reject(error);
        } else {
          resolve(results[0] || { total_tables: 0, available_tables: 0, occupied_tables: 0, reserved_tables: 0 });
        }
      });
    });
  },

  // 更新桌位状态
  updateTableStatus: (tableId, status) => {
    return new Promise((resolve, reject) => {
      const query = 'UPDATE table_info SET status = ?, updated_at = NOW() WHERE id = ?';
      db.query(query, [status, tableId], (error, results) => {
        if (error) {
          console.error('更新桌位状态失败:', error);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },

  // 根据桌位ID获取桌位信息
  getTableById: (tableId) => {
    return new Promise((resolve, reject) => {
      const query = 'SELECT * FROM table_info WHERE id = ?';
      db.query(query, [tableId], (error, results) => {
        if (error) {
          console.error('获取桌位信息失败:', error);
          reject(error);
        } else {
          resolve(results[0]);
        }
      });
    });
  }
};

module.exports = Table;